import { mountStoreDevtool } from 'simple-zustand-devtools';
import { StateCreator, create } from 'zustand';

import { login } from '../api/user/index';
import { persist } from 'zustand/middleware';
import layoutStore from './layoutStore';

type LoginDataType = { username: string; password: string; typeNumber: number };

interface LoginStore {
  user: unknown;
  token: string;
  loading: boolean;
  login: (data: LoginDataType) => void;
  outLogin: () => void;
  setLoading: () => void;
  returnUser: () => any;
}

let store: StateCreator<LoginStore> = (set: any, get: any) => ({
  loading: false,
  user: null,
  token: '',
  login: async (data: LoginDataType) => {
    set({ loading: true });
    const userRes = (await login(data).catch((err) => {
      console.log(err);
      set({ loading: false });
    })) as any;
    if (userRes?.success) {
      set({
        user: userRes?.data.userInfo.userInForm,
        token: userRes?.data.token,
      });
      set({ loading: false });
      const { setLoadingMenus } = layoutStore.getState();
      setLoadingMenus(true);
    } else {
      set({ loading: false });
    }
  },
  outLogin: () => {
    localStorage.clear();
  },
  setLoading() {
    set({ loading: false });
  },
  returnUser: () => {
    return get().user;
  },
});

store = persist(store, { name: 'useUserStore' });

const useUserStore = create<LoginStore>(store);
mountStoreDevtool('useUserStore', useUserStore);
export default useUserStore;
